<?php
namespace App\Blocks;

use App\Models\CrowdArticle;
use App\Models\CrowdArticleComment;
use App\Models\CrowdArticleUsefulLog;
use App\Models\Users;
use DB;
use EasyWeChat\Kernel\Messages\Article;

class ArticleBlock {

    public function getArticleList($search = [], $page = 1, $pageSize = 20){
        $articleModel = new CrowdArticle();

        $sql = DB::table($articleModel->getTable())
            ->select(
                'id',
                'crowd_id',
                'title',
                'introduce',
                'content',
                'headimgurl',
                'useful',
                'comment',
                'share',
                'views',
                'created_at'
            );

        if(isset($search['crowd_id'])){
            $sql->where('crowd_id', $search['crowd_id']);
        }

        if(isset($search['recommend'])){
            $sql->where('is_recommend', $search['recommend']);
        }

        $data = $sql->whereNull('deleted_at')
            ->orderBy('created_at', 'desc')
            ->skip(($page - 1) * $pageSize)->take($pageSize)
            ->get();

        foreach ($data as $datas){
            $datas->title = $this->mogo_cut_str($datas->title,22);
            $datas->introduce = $this->mogo_cut_str($datas->introduce,31);
        }

        return $data;
    }

    private function mogo_cut_str($sourcestr,$cutlength)
    {
        $returnstr='';
        $i=0;
        $n=0;
        $str_length=strlen($sourcestr);
        while (($n<$cutlength) and ($i<=$str_length))
        {
            $temp_str=substr($sourcestr,$i,1);
            $ascnum=Ord($temp_str);
            if ($ascnum>=224)
            {
                $returnstr=$returnstr.substr($sourcestr,$i,3);
                $i=$i+3;
                $n++;
            }
            elseif ($ascnum>=192)
            {
                $returnstr=$returnstr.substr($sourcestr,$i,2);
                $i=$i+2;
                $n++;
            }
            elseif ($ascnum>=65 && $ascnum<=90)
            {
                $returnstr=$returnstr.substr($sourcestr,$i,1);
                $i=$i+1;
                $n++;
            }
            else
            {
                $returnstr=$returnstr.substr($sourcestr,$i,1);
                $i=$i+1;
                $n=$n+0.5;
            }
        }
        if ($str_length>$i){
            $returnstr = $returnstr . "...";
        }
        return $returnstr;
    }


    //文章详情
    public function getArticleInfo($id,$uid){
        $articleModel = new CrowdArticle();
        $ArticleUsefulModel = new CrowdArticleUsefulLog();
        //添加浏览次数
        $view = DB::table($articleModel->getTable())->where('id',$id)->increment('views');
        if (!$view){
            return false;
        }
        //是否点赞
        $usefulData = DB::table($ArticleUsefulModel->getTable())->where('article_id',$id)->where('user_id',$uid)->first();
        if ($usefulData){
            $is_useful = 1;
        }else{
            $is_useful = 0;
        }
        //返回文章数据
        $articleInfo = DB::table($articleModel->getTable())->where('id', $id)
            ->whereNull('deleted_at')
            ->first();

        $articleInfo->is_useful = $is_useful;
        $articleInfo->content = htmlspecialchars_decode($articleInfo->content);
        return $articleInfo;
    }

    public function getArticleComment($search = [], $page = 0, $pageSize = 20){
        $articleCommentModel = new CrowdArticleComment();
        $userModel = new Users();
        $sql = DB::table($articleCommentModel->getTable() . ' as ac')
            ->select(
                'ac.*',
                'u.nick_name',
                'u.headimgurl'
            )
            ->leftJoin($userModel->getTable() . ' as u', 'ac.user_id', '=', 'u.id')
            ->whereNull('ac.deleted_at');
        if(isset($search['article_id'])){
            $sql->where('article_id', $search['article_id']);
        }
        if(isset($search['user_id'])){
            $sql->where('user_id', $search['user_id']);
        }

        $comment = $sql->orderBy('updated_at', 'desc')
            ->take(($page - 1) * $pageSize)->take($pageSize)
            ->get();

        return $comment;
    }

    public function useful($userId, $articleId){
        try {
            DB::beginTransaction();
            $usefulModel = new CrowdArticleUsefulLog();
            $articleModel = new CrowdArticle();

            if(DB::table($usefulModel->getTable())->insert([
                    'user_id' => $userId,
                    'article_id' => $articleId
                ]) === false){
                return false;
            }

            if(DB::table($articleModel->getTable())->where('id', $articleId)->increment('useful') === false){
                DB::rollBack();
                return false;
            }

            DB::commit();
            return true;
        }catch (\Exception $exception){
            DB::rollBack();
            \Log::error($exception);
            return false;
        }
    }

    //创建文章评论
    public function createComment($data){
        $ArticleCommentModel = new CrowdArticleComment();
        $UserModel = new Users();
        $ArticleModel = new CrowdArticle;

        try{
            DB::beginTransaction();
            //添加评论
            $commentId = DB::table($ArticleCommentModel->getTable())
                ->insertGetId($data);
            if (!$commentId){
                DB::rollBack();
                return false;
            }

            //添加评论数
            $commentNum = DB::table($ArticleModel->getTable())->where('id',$data['article_id'])->increment('comment');
            if (!$commentNum){
                DB::rollBack();
                return false;
            }

            //返回评论信息
            DB::commit();
            $commentUser = DB::table($ArticleCommentModel->getTable().' as a')
                ->select(
                    'a.article_id',
                    'a.user_id',
                    'a.content',
                    'a.created_at',
                    'u.nick_name',
                    'u.headimgurl'
                )
                ->leftJoin($UserModel->getTable().' as u','a.user_id','=','u.id')
                ->where('a.id',$commentId)
                ->first();
            return $commentUser;

        }catch (\Exception $exception){
            DB::rollBack();
            \Log::error($exception);
            return false;
        }

    }
}
